package com.lagou.filter;/**
 * Created by IntelliJ IDEA.
 * User: Yangdx.
 * Date: 2020/7/25.
 * Time: 3:04.
 * Tags: Code, we are serious.
 */

import com.lagou.util.HttpResponseStatusUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author
 * @create 2020-07-25 3:04
 **/
public class CombineAuthFromCookieFilter extends HttpResponseStatusUtil implements GlobalFilter, Ordered {
    @Value("${config.cookie.name.token}")
    private String tokenTagName;

    @Value("${api.autoCombine}")
    private String[] autoCombineApis;

    @Value("${config.response.message.unauthorize}")
    private String unauthorizeText;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        for (String autoCombineApi : autoCombineApis) {
            if (path.matches(autoCombineApi)) {
                return doFilter(exchange, chain);
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        if (!cookies.containsKey(tokenTagName)) {
            return responseStatusAndMessage(exchange.getResponse(), HttpStatus.UNAUTHORIZED, unauthorizeText);
        }

        ServerHttpRequest newRequest = request.mutate()
                .path(path + "/" + cookies.getFirst(tokenTagName).getValue())
                .build();
        return chain.filter(exchange.mutate().request(newRequest).build());
    }
}
